//
//  SWScanController.swift
//  SinaWeibo
//
//  Created by wszyxc on 16/7/21.
//  Copyright © 2016年 wszyxc. All rights reserved.
//

import UIKit

import SnapKit

import AVFoundation


class SWScanController: UIViewController {
    
    var qrcodeBtn:SWUpDownButton?
    var barcodeBtn:SWUpDownButton?

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
        setupNav()
        
        setupToolBar()
        
        setupAnimation()
        
        startScan()

    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
       
    }
    
    private func setupAnimation(){
        
        UIView.animateWithDuration(1) { () -> Void in
            
            UIView.setAnimationRepeatCount(MAXFLOAT)
            
            self.scanImageView.snp_updateConstraints(closure: { (make) -> Void in
                
                
                make.top.equalTo(self.qrcodeBorderImageView).offset(0)
                
            })
            
            self.scanImageView.layoutIfNeeded()
            
        }

    }
    
    private func setupToolBar(){
        
        view.addSubview(toolBar)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            
            make.leading.trailing.bottom.equalTo(view).offset(0)
            
            make.height.equalTo(49)

            
        }
        
    }
    
    private func setupUI(){
        
        view.backgroundColor = UIColor.blackColor()
        
        view.addSubview(qrcodeView)
        
        setupLayoutOfQrcodeView()
        
    }
    
    private func setupLayoutOfQrcodeView(){
        
        qrcodeBorderImageView.snp_makeConstraints(closure: { (make) -> Void in
            
            make.leading.trailing.equalTo(view).offset(0)
            
            make.height.equalTo(300)
            
            make.center.equalTo(view.snp_center)
            
        })
        
        scanImageView.snp_makeConstraints(closure: { (make) -> Void in
            
            make.leading.trailing.equalTo(view).offset(0)
            
            make.width.equalTo(375)
            
            make.height.equalTo(300)
            
            make.top.equalTo(qrcodeBorderImageView.snp_top).offset(-300)
        })

        
        
    }
    
    private lazy var qrcodeView:UIView = {
        
      //  [weak self] in
        let qrcodeView:UIView = UIView()
        
        //添加二维码边
        qrcodeView.addSubview(self.qrcodeBorderImageView)
        
        //添加扫描效果图片
        qrcodeView.addSubview(self.scanImageView)
        
        return qrcodeView
    }()
    
    private lazy var qrcodeBorderImageView:UIImageView = {
        
        let imageView = UIImageView(image: UIImage(named: "qrcode_border"))
        
        return imageView
        
    }()
    
    private lazy var scanImageView:UIImageView = {
        
       let scanImageView = UIImageView(image: UIImage(named: "qrcode_scanline_barcode"))
        
        
        return scanImageView
    }()
    
    
    private func setupNav(){
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: nil, title: "关闭", target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: nil, title: "相册", target: self, action: "photos")
        
        navigationController?.navigationBar.barTintColor = UIColor.blackColor()
        
        
    }
    
  @objc  private func close(){
        
       print("关闭扫描")
       navigationController?.dismissViewControllerAnimated(true, completion: nil)
        
    }
    
  @objc  private func photos(){
        
        print("打开相册")
    
        fromAlbum()
    
    }
    
    private lazy var toolBar:UIToolbar = {
       
        let toolBar:UIToolbar = UIToolbar()
    
        toolBar.barTintColor = UIColor.blackColor()
        
        
//        let item1:UIBarButtonItem = UIBarButtonItem(customView:SWUpDownButton(imageName: "qrcode_tabbar_icon_qrcode", selectImageName: "qrcode_tabbar_icon_qrcode_highlighted", title: "二维码", frame: CGRectMake(0, 0, ScreenWidth/2, 49),isSelected:true,target:self,action:"qrcodeClick"))
//        
        let spaceItem:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
        
//        let item2:UIBarButtonItem = UIBarButtonItem(customView: SWUpDownButton(imageName: "qrcode_tabbar_icon_barcode", selectImageName: "qrcode_tabbar_icon_barcode_highlighted", title: "条形码", frame: CGRectMake(0, 0, ScreenWidth/2, 49),isSelected:false,target:self,action:"barcodeClick"))
   
        toolBar.items = [spaceItem,self.qrItem,spaceItem,self.barcodeItem,spaceItem]
        
        return toolBar
      
    }()
    
    //懒加载toolBar上面的二维码item
    lazy var qrItem:UIBarButtonItem = {
        
        self.qrcodeBtn = SWUpDownButton(imageName: "qrcode_tabbar_icon_qrcode", selectImageName: "qrcode_tabbar_icon_qrcode_highlighted", title: "二维码", frame: CGRectMake(0, 0, ScreenWidth/2, 49),isSelected:true,target:self,action:"qrcodeClick:")
        
         let item1:UIBarButtonItem = UIBarButtonItem(customView:self.qrcodeBtn!)
        
        return item1
    }()
    
    //懒加载toolBar上面的条形码item
    lazy var barcodeItem:UIBarButtonItem = {
        
        self.barcodeBtn = SWUpDownButton(imageName: "qrcode_tabbar_icon_barcode", selectImageName: "qrcode_tabbar_icon_barcode_highlighted", title: "条形码", frame: CGRectMake(0, 0, ScreenWidth/2, 49),isSelected:false,target:self,action:"barcodeClick:")
        
       let item2:UIBarButtonItem = UIBarButtonItem(customView:self.barcodeBtn!)
        
        return item2
    }()
    
    
    @objc private func qrcodeClick(button:UIButton){
        
        self.qrcodeBtn?.selected = true
        
        self.barcodeBtn?.selected = false
    }
    
    @objc private func barcodeClick(button:UIButton){
        
        self.qrcodeBtn?.selected = false
        
        self.barcodeBtn?.selected = true
    }
    

    
    deinit{
        
        print("销毁了")
    }
    
    
    // MARK: - 懒加载
    // 会话
    //    private lazy var session : AVCaptureSession = AVCaptureSession()
    
    private lazy var session: AVCaptureSession = AVCaptureSession()
    
    // 拿到输入设备
    private lazy var deviceInput: AVCaptureDeviceInput? = {
        // 获取摄像头
        let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        do{
            // 创建输入对象
            let input = try AVCaptureDeviceInput(device: device)
            return input
        }catch
        {
            print(error)
            return nil
        }
    }()
    
    // 拿到输出对象
    private lazy var output: AVCaptureMetadataOutput = AVCaptureMetadataOutput()
    
    // 创建预览图层
    private lazy var previewLayer: AVCaptureVideoPreviewLayer = {
        let layer = AVCaptureVideoPreviewLayer(session: self.session)
        layer.frame = UIScreen.mainScreen().bounds
        return layer
    }()

}


//这里写打开相册的功能
extension SWScanController:UINavigationControllerDelegate,UIImagePickerControllerDelegate{
    
 
    //选取相册
     func fromAlbum() {
        //判断设置是否支持图片库
        if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
            //初始化图片控制器
            let picker = UIImagePickerController()
            //设置代理
            picker.delegate = self
            //指定图片控制器类型
            picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
            //设置是否允许编辑
            picker.allowsEditing = true
            //弹出控制器，显示界面
            self.presentViewController(picker, animated: true, completion: {
                () -> Void in
            })
        }else{
            print("读取相册错误")
        }
        
    }
    
    //选择图片成功后代理
//    func imagePickerController(picker: UIImagePickerController,
//        didFinishPickingMediaWithInfo info: [String : AnyObject]) {
//            //查看info对象
//            print(info)
//            //获取选择的原图
//            let image = info[UIImagePickerControllerOriginalImage] as! UIImage
//            imageView.image = image
//            //图片控制器退出
//            picker.dismissViewControllerAnimated(true, completion: {
//                () -> Void in
//            })
//    }
    
}

// MARK: - 二维码扫描
extension SWScanController{
    
    /**
     扫描二维码
     */
    private func startScan(){
        
        // 1.判断是否能够将输入添加到会话中
        if !session.canAddInput(deviceInput)
        {
            return
        }
        // 2.判断是否能够将输出添加到会话中
        if !session.canAddOutput(output)
        {
            return
        }
        // 3.将输入和输出都添加到会话中
        session.addInput(deviceInput)
        print(output.availableMetadataObjectTypes)
        session.addOutput(output)
        print(output.availableMetadataObjectTypes)
        
        // 4.设置输出能够解析的数据类型
        // 注意: 设置能够解析的数据类型, 一定要在输出对象添加到会员之后设置, 否则会报错
        output.metadataObjectTypes =  output.availableMetadataObjectTypes
        print(output.availableMetadataObjectTypes)
        // 5.设置输出对象的代理, 只要解析成功就会通知代理
        output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
        
        // 添加预览图层
        view.layer.insertSublayer(previewLayer, atIndex: 0)
        
        // 6.告诉session开始扫描
        session.startRunning()
    }
    
    



}


extension SWScanController: AVCaptureMetadataOutputObjectsDelegate
{
    // 只要解析到数据就会调用
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!)
    {
        // 注意: 要使用stringValue
        print(metadataObjects.last?.stringValue)
//        resultLabel.text = metadataObjects.last?.stringValue
//        resultLabel.sizeToFit()
    }
}



